const Router = require('koa-router')
const login = new Router()
const db = require('../util/db')

//引入生成token模块
const jwt = require('jsonwebtoken')

//引入处理post参数的模块
const bodyparser = require('koa-bodyparser')

//中间件调用bodyparser模块
login.use(bodyparser())

login.post('/register', async (cxt) => {
    //获取前端发送过来的数据
    let account = cxt.request.body.account //用户名
    let pwd = cxt.request.body.pwd //密码


    //查询数据库 判断用户是否存在
    let data = await new Promise((resovle, reject) => {
        let sql = `select * from users where account='${account}'`
        return db.query(sql, (err, result) => {
            if (err) throw err

            resovle(result)
        })
    })
    //数组大于0 为存在, 判断 密码是否正确,
    if(data.length > 0) {
        //验证密码
        if(data[0].pwd == pwd) {
            cxt.body = {
                token: data[0].token,
                msg: '用户登录成功',
                account,
            }
        }else {
            cxt.body = {
               msg: "账号或密码错误"
            }
        }
    }else { //小于0, 用户不存在,执行注册操作
         //生成token jwt.sign(对象一, 加密方式, 有效期限对象)
         let userToken = jwt.sign({account, pwd}, 'secret', {expiresIn: 3600})
            
         let sql =  `insert into users (account, pwd, token) values ('${account}', '${pwd}', '${userToken}')`

        let result = await new Promise((resolve, reject) => {
            //插入数据库
            return db.query(sql, (err, res) => {
                if(err) throw err
                let obj = {
                    token:userToken,
                    msg: '用户注册成功',
                    account,
                }
                resolve(obj)
            })
        })
        cxt.body = result
    }
})

module.exports = login